const {
  addAnswer,
  isExist,
  getAnswers,
  getAnswerById,
  deleteAnswerById,
  deleteAnswersByIds,
  updateAnswerById,
  getPaperAnswersCount,
} = require('../models/answerModel');
const {
  updatePaperAnswers,
  getPaperAnswersid,
  getPaperById,
} = require('../models/paperModel');

module.exports = {
  // 添加答卷的处理函数
  async addAnswer(req, res) {
    // console.log(req.user._id);
    const {
      paperinfo: { items, titleinfo },
    } = await getPaperById(req.body.paperid, {
      'paperinfo.items': 1,
      'paperinfo.titleinfo': 1,
    });
    // console.log(items);
    // console.log(JSON.stringify(items[1]));

    Object.keys(req.body.answerInfo).forEach(async key => {
      console.log(typeof req.body.answerInfo[key]);
      if (typeof req.body.answerInfo[key] === 'object') {
        req.body.answerInfo[key].forEach(el => {
          items[key.slice(1) - 1][el]++;
        });
      } else if (
        titleinfo[key.slice(1) - 1].name === '填空' ||
        titleinfo[key.slice(1) - 1].name === '打分'
      ) {
        items[key.slice(1) - 1][req.body.answerInfo[key]] = 1;
      } else {
        items[key.slice(1) - 1][req.body.answerInfo[key]]++;
      }
    });
    // console.log(items);

    const createRes = await addAnswer(req.body);
    const updatePaperinfo = await updatePaperAnswers(req.body.paperid, {
      $addToSet: { answersid: createRes._id },
      $set: { 'paperinfo.items': items },
    });
    if (!createRes || !updatePaperinfo)
      return res.sendMess('添加失败，请稍后再试！');
    res.send({
      meta: { msg: '添加成功!', status: 200 },
      data: { id: createRes._id },
    });
    // res.sendMess('添加成功!', 201);
  },
  // 获取答卷的处理函数
  async getAnswers(req, res) {
    //获取当前用户的答卷id
    const answersid = await getPaperAnswersid(req.params.paperid);
    const count = await getPaperAnswersCount(answersid);
    const result = await getAnswers(answersid);
    if (!result) return res.sendMess('获取答卷信息失败！');
    res.send({
      meta: { msg: '获取答卷成功！', status: 200 },
      data: { answers: result, count },
    });
  },

  // 根据ID编辑答卷信息
  async updateAnswerById(req, res) {
    const result = await updateAnswerById(req.params.id, req.body);
    if (!result.modifiedCount) {
      return res.sendMess('修改答卷失败！');
    }
    res.sendMess('修改答卷成功！', 200);
  },
};
